<template>
  <CustomDialog ref="customDialog" width="600px" :title="dialogProps.title" :isView="dialogProps.isView"
    :onSubmit="handleSubmit" :onClose="handleClose">
    <template #header>
      {{ `${dialogProps.title}职位` }}
    </template>
    <template #content>
      <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :disabled="dialogProps.isView"
        :model="dialogProps.row" :hide-required-asterisk="dialogProps.isView">
        <el-form-item label="职位名称" prop="jobName">
          <BInput v-model="dialogProps.row!.jobName" placeholder="请输入职位名称" clearable :inputProps="{ maxlength: 50 }" />
        </el-form-item>
        <el-form-item label="关联角色" prop="roleIds">
          <el-select v-model="dialogProps.row!.roleIds" placeholder="请选择角色" multiple clearable>
            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联部门" prop="deptId">
          <el-tree-select v-model="dialogProps.row!.deptId" :data="treeSelectData" filterable check-strictly
            :props="treeSelectProps" :default-value="dialogProps.row.deptId" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <BInput v-model="dialogProps.row!.remark" placeholder="请输入文字" type="textarea" clearable />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="customDialog?.acceptParams(false)">取消</el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import CustomDialog from "@/components/Dialog/CustomDialog.vue";
import BInput from "@/components/BaseComponents/BInput.vue";
import { getOrganicTree } from "@/api/modules/organize"
// import { getAllRoleList } from '@/api/basic/role'
import { useDataStore } from '@/stores/modules/data'
import { getJobDetail } from "@/api/basic/position";

const dataStore = useDataStore()

const rules = reactive({
  jobName: [{ required: true, message: "职位名称必填" }],
  roleIds: [{ required: true, message: "关联角色必选" }],
  deptId: [{ required: true, message: "关联部门必选" }],
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {},
});

const customDialog = ref<InstanceType<typeof CustomDialog>>();

// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
  // dialogProps.value = params;
  //修改，使新增时数据不清除
  dialogProps.value.api = params.api;
  dialogProps.value.getTableList = params.getTableList;
  dialogProps.value.title = params.title;
  dialogProps.value.isView = params.isView;

  if (JSON.stringify(params.row) !== '{}') {
    if (JSON.stringify(params.row) !== '{}') {
      const res: any = await getJobDetail(params.row.id);
      dialogProps.value.row = { ...res };
      // dialogProps.value.row.roleIds = ['64', '59']
      // dialogProps.value.row.roles = res.role.map((role: any) => ({
      //   roleId: role.id,
      //   roleName: role.roleName
      // }));
    }
  }
  customDialog.value?.acceptParams(true);
};

interface TreeNode {
  id: number;
  parentDepartmentId: number;
  deptName: string;
  departmentType: number;
  children?: TreeNode[];
}

interface TreeSelectNode {
  value: number;
  label: string;
  children?: TreeSelectNode[];
}

//转换为树形结构
const convertToTreeSelectData = (data: TreeNode[]): TreeSelectNode[] => {
  return data.map(node => {
    const treeSelectNode: TreeSelectNode = {
      value: node.id,
      label: node.deptName,
      children: node.children ? convertToTreeSelectData(node.children) : undefined
    };
    return treeSelectNode;
  });
}

onMounted(async () => {
  await dataStore.fetchRoleList();
  await dataStore.fetchDepartmentList()
});

const roleList = computed(() => dataStore.roleList);
const departmentList = computed(() => dataStore.departmentList);

// // 获取部门树
const treeSelectData = ref<TreeSelectNode[]>([]);
const getOrganicTreeList = async () => {
  try {
    const res = await getOrganicTree();

    treeSelectData.value = convertToTreeSelectData(res);
  } catch (error) {
    console.log('获取部门列表失败', error);
  }
}
getOrganicTreeList()

// //获取全部角色
// const roleList = ref<any>([])
// const getRoleList = async () => {
//   try {
//     const res = await getAllRoleList();
//     roleList.value = res;
//   } catch (error) {
//     console.log('获取角色列表失败', error);

//   }
// };
// getRoleList()


/**
 * 将包含角色对象和角色 ID 字符串的数组转换为角色 ID 数组
 * @param roles - 包含角色对象和角色 ID 字符串的数组
 * @returns 角色 ID 数组
 */
const convertRolesToRoleIds = (roles: Array<{ roleId: number; roleName: string } | string>): number[] => {
  return roles.map((role) => {
    if (typeof role === 'object') {
      return role.roleId;
    } else if (typeof role === 'string') {
      return parseInt(role, 10);
    }
  }).filter(Boolean) as number[]; // 过滤掉可能的 undefined 值
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    // // 将角色名称转换为角色 ID
    // dialogProps.value.row.roles = convertRolesToRoleIds(dialogProps.value.row.roles);
    // dialogProps.value.row.roleIds = dialogProps.value.row.roles;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}职位成功！` });
      dialogProps.value.getTableList!();
      customDialog.value?.acceptParams(false);
      ruleFormRef.value?.resetFields();
    } catch (error) {
      console.log(error);
    }
  });
};

const handleClose = () => {
  customDialog.value?.acceptParams(false);
  if (dialogProps.value.title !== '新增') {
    dialogProps.value.row = {}
  }
};

const treeSelectProps = {
  value: 'value',
  label: 'label',
  children: 'children'
};

defineExpose({
  acceptParams
});
</script>
